package com.wcl.rabbit.producer.component;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

@Component
public class RabbitSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 确认消息的回调监听接口，用于确认消息是否被broker所收到
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){
        /**
         *
         * @param correlationData 作为一个唯一标识
         * @param b broker是否落盘成功
         * @param s 失败的一些异常信息
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean b, String s) {
            System.out.println("ACK:"+b+"course"+s);
        }
    };

    /**
     * 对外发送消息方法
     * @param message 消息内容
     * @param properties 附加属性
     * @throws Exception
     */
    public void send (Object message, Map<String,Object> properties) throws Exception{
        MessageHeaders mhs = new MessageHeaders(properties);

        //构造消息
        Message<?> msg = MessageBuilder.createMessage(message,mhs);

        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());

        //设置回调监听
        rabbitTemplate.setConfirmCallback(confirmCallback);

        rabbitTemplate.convertAndSend("exchange-1", "springboot.rabbit", msg, new MessagePostProcessor() {
            @Override
            public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
                System.out.println("post to do:"+message);
                return message;
            }
        },cd);

    }




}
